import React, { Component } from 'react'
import BaseLayout from './baseLayout';
import { connect } from 'dva';
import {hideDingTalkHead,isDingTalk,dingTalkBack,} from 'utils/utils'
import { ENTER_TYPE } from 'utils/Enum'
import {
  Modal,

} from 'antd-mobile';
const alert = Modal.alert;
const ULR_NO_LAYOUT = ['/', '/signature'];
import createMemoryHistory from 'history/createMemoryHistory'


const pathShouldHideDingHead=['/EnterpriseCertificationInformation',
  '/EnterpriseCertificationList',
  '/EnterpriseCertificationListBackUps',
  '/EnterpriseCertificationResult',
  '/ImpressionLibrary',
  '/PersonalCertification',
  '/PersonalCertificationAlipayDetail',
  '/PersonalCertificationDetail',
  '/RealNameAuthenticationResult',
  '/uploadImg',
  '/Signature',
  '/SignCertification',
  '/Authentication',
  '/editImg',
  '/SignTheSuccess',
  '/SignTheSuccess/SignatureViewer',
  '/SignCertificationResults',
  '/SignatureDetail',
]
import { CERTIFICATION_TYPE,PROCESS_STATUS } from 'utils/Enum';

import * as dd from 'dingtalk-jsapi';

@connect(({ basicLayoutModel ,pdfModel}) => ({ basicLayoutModel,pdfModel }))
class Index extends Component {
  componentDidMount() {
    localStorage.setItem('isDingTalk',isDingTalk())
    if(isDingTalk()){
      this.getJsapiSign()
    }
  }
  getJsapiSign=()=>{
    const {dispatch}=this.props;
    let url = window.location.href
    if (url.indexOf("#/") > -1) {
      url = url.substr(0, url.indexOf("#/"))
    }
    let corpId=localStorage.getItem('corpId')
    dispatch({
      type:'pdfModel/getJsapiSign',
      payload:{
        // url:encodeURIComponent(url),
        url,
        corpId
      },
      callback:(res)=>{
        const {agentId,timeStamp,nonceStr,signature}=res;
        const jsApiList = [
          "device.notification.prompt",
          "device.notification.actionSheet",
          "runtime.permission.requestOperateAuthCode",
          "biz.navigation.quit",
          "biz.util.openModal",
          "biz.util.openSlidePanel",
          "biz.util.downloadFile",
          "biz.util.openLocalFile",
          "biz.util.isLocalFileExist",
          "biz.util.ut",
          "biz.customContact.choose",
          "biz.customContact.multipleChoose",
          "runtime.permission.requestAuthCode",
          "service.request.httpOverLwp",
          "device.notification.alert",
          "device.notification.showPreloader",
          "device.notification.hidePreloader",
          "device.notification.confirm",
          "device.notification.toast",
          "biz.util.datepicker",
          "biz.util.timepicker",
          "biz.util.datetimepicker",
          "biz.ding.post",
          "biz.telephone.call",
          "biz.telephone.showCallMenu",
          "biz.user.get",
          "biz.contact.choose",
          "biz.contact.createGroup",
          "biz.contact.complexChoose",
          "biz.contact.complexPicker",
          "biz.contact.departmentsPicker",
          "biz.contact.externalComplexPicker",
          "biz.util.chosen",
          "biz.util.openLink",
          "biz.util.open",
          "biz.util.uploadImage",
          "biz.util.previewImage",
          "biz.util.share",
          "biz.navigation.back",
          "biz.navigation.setTitle",
          "biz.navigation.setLeft",
          "biz.navigation.setRight",
          "biz.navigation.close",
          "biz.chat.pickConversation",
          "biz.chat.chooseConversation",
          "biz.chat.toConversation",
          "biz.clipboardData.setData",
          "biz.chat.chooseConversationByCorpId",
          "biz.navigation.setIcon",
          "biz.util.scan",
          "biz.chat.openSingleChat",
          "biz.cspace.saveFile",
          "biz.util.uploadAttachment",
          "biz.ding.create",
          "ui.progressBar.setColors",
          "ui.pullToRefresh.disable",
          "ui.webViewBounce.disable",
          "ui.input.plain",
        ]
        dd.config({
          agentId: agentId,
          corpId: res.corpId || corpId,
          timeStamp: timeStamp,
          nonceStr:nonceStr,
          signature:signature,
          jsApiList
        })
        dd.ready((res) => {console.log(res)})
        dd.error(err => {console.log(err)})
      }
    })
  }

  componentDidUpdate() {
    const History=createMemoryHistory();
    History.listen(this.routeChangeHandler(this.props.history.location,this.props.history.action))
  }

  routeChangeHandler=(location,action) =>{
    let lastPath=window.localStorage.getItem('currentPath')||''
    if(lastPath!==window.location.pathname){
      let  historyLength=window.sessionStorage.getItem('historyLen');
      let historyLen;
      if(historyLength!=='0'){
        if(!historyLength){
          historyLen=1;
        }
        else{
          historyLen=Number(historyLength);
        }
      }
      else{
        historyLen=0;
      }
      if (action === 'PUSH') {
        historyLen++
      }
      if (action === 'POP')  {
        historyLen--
      }
      if(historyLen<0||historyLen===0){
        window.sessionStorage.historyLen = 1
      }
      else{
        window.sessionStorage.historyLen = historyLen
      }
      window.localStorage.currentPath=window.location.pathname;
    }

  }
  renderBody = () => {

    const {location: {pathname}, children } = this.props;
    const enterType=localStorage.getItem('enterType');
    const isExternal = enterType === ENTER_TYPE.EXTERNAL? true : false

    // const history=router.createBrowserHistory();
    // const history = router.;
    // history.listen(()=>{
    //   let backStep=localStorage.getItem('backStep');
    //   let backStepNum=Integer.parseInt(backStep)
    //   if(history.action!=='POP'){
    //     localStorage.setItem('backStep',backStep+1)
    //   }
    //   else{
    //     localStorage.setItem('backStep',backStep-1)
    //   }
    // })
    // const isDingTalk=localStorage.getItem("isDingTalk");
    // if (pathShouldHideDingHead.includes(pathname)) {
    //   if(isDingTalk()){
    //     hideDingTalkHead();
    //   }
    // }
    // if(pathname==='/EnterpriseCertificationInformation'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       router.push(`/EnterpriseCertificationListBackUps`)
    //     });
    //   }
    // }
    // else if(pathname==='/EnterpriseCertificationList'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       console.log('pathname',pathname)
    //       e.preventDefault();
    //       if(isExternal) {
    //         dingTalkBack(localStorage.getItem("returnUrl"))
    //       } else {
    //         router.push('/Signature')
    //       }
    //     })
    //   }
    //
    // }
    // else if(pathname==='/EnterpriseCertificationListBackUps'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       router.push(`/EnterpriseCertificationList`)
    //     })
    //   }
    // }
    // else if(pathname==='/ImpressionLibrary'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       console.log('pathname',pathname)
    //
    //       e.preventDefault();
    //       if(isExternal) {
    //         dingTalkBack(localStorage.getItem("returnUrl"))
    //       } else {
    //         router.push(`/Signature`)
    //       }
    //     })
    //   }
    //
    // }
    // else if(pathname==='/PersonalCertification'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       if(isExternal) {
    //         dingTalkBack(localStorage.getItem("returnUrl"))
    //       } else {
    //         router.push(`/EnterpriseCertificationListBackUps`)
    //       }
    //     });
    //   }
    // }
    // else if(pathname==='/PersonalCertificationAlipayDetail'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       const {location:{query:{type,url,Certification}}}=this.props
    //       router.push(`/PersonalCertification?url=${url}&type=${type}&Certification=${Certification}`)
    //     });
    //   }
    // }
    // else if(pathname==='/PersonalCertificationDetail'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       const {location:{query:{type,url,Certification}}}=this.props
    //       router.push(`/PersonalCertification?url=${url}&type=${type}&Certification=${Certification}`)
    //     });
    //   }
    // }
    // else if(pathname==='/RealNameAuthenticationResult') {
    //   if (isDingTalk) {
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       const {  result, Certification } = this.props
    //       let url=''
    //       if(Certification === CERTIFICATION_TYPE.INTEND_CERTIFICATION){
    //         url='/Signature?result='+result
    //       }else {
    //         url='/EnterpriseCertificationListBackUps'
    //       }
    //       router.push(url)
    //
    //     });
    //   }
    // }
    // else if(pathname==='/uploadImg'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       if(isExternal) {
    //         dingTalkBack(localStorage.getItem("returnUrl"))
    //       } else {
    //         router.push('/Signature')
    //       }
    //
    //     });
    //   }
    //
    // }
    // else if(pathname==='/Signature'){
    //   if(isDingTalk){
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       // 在这里处理你的业务逻辑
    //       console.log('pathname',pathname)
    //         // window.location.href = url
    //       dingTalkBack(localStorage.getItem("returnUrl"))
    //
    //     });
    //   }
    // }
    // else if(pathname==='/SignTheSuccess/SignatureViewer'){
    //   let url =localStorage.getItem("returnUrl");
    //   if(isDingTalk){
    //     console.log('pathname',pathname)
    //     document.addEventListener('backbutton', function(e) {
    //       e.preventDefault();
    //       dingTalkBack(localStorage.getItem("returnUrl"))
    //
    //
    //     });
    //   }
    // }

    if (ULR_NO_LAYOUT.includes(pathname)) {
      // dispatch({
      //   type:'basicLayoutModel/save',
      //   payload:{
      //     pathname
      //   }
      // })
      // return  (<BaseLayout {...this.props} />);
    }
    return (
      <React.Fragment>
        {children}
      </React.Fragment>
    );
  }

  render() {

    return (
      <React.Fragment>
        {this.renderBody()}
      </React.Fragment>
    )
  }
}

export default Index;
